﻿using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Colorful.CMS.Core
{
    public static class ColorCms
    {
        public static void Run<TStartup>(string[] args, Func<IWebHostBuilder, IWebHostBuilder> builderCallback = null) where TStartup : ColorCmsStartup
        {
            WebConfig.RootPath = Directory.GetCurrentDirectory();
            var builder = WebHost.CreateDefaultBuilder(args);
            if (builderCallback != null)
                builder = builderCallback(builder);
            builder.ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);
                    config.AddJsonFile($"appsettings.dist.json", optional: true, reloadOnChange: true);
                    builderContext.Configuration.GetReloadToken().RegisterChangeCallback(_ =>
                    {
                        ColorCmsStartup.Current.LoadSettings(true);
                    }, null);
                })
                .UseKestrel(options =>
                {
                    //options.Limits.MinRequestBodyDataRate =
                    //    new MinDataRate(500, TimeSpan.FromSeconds(5));
                    options.AddServerHeader = false;
                })
                //.UseUrls() 设置绑定域名
                .UseContentRoot(WebConfig.RootPath)
                .UseStartup<TStartup>()
                .UseApplicationInsights()
                .Build()
                .Run();
        }
    }
}
